<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
        * {
            font-family: simhei;
        }

        #app {
            max-width: 640px;
            margin: 50px auto;
        }

        #child-component {
            display: none;
        }

        .parent-content,
        .child-content {
            height: 150px;
            padding: 20px;
        }

        .parent-content {
            border: 1px solid #0090D3;
            margin-bottom: 20px;
        }

        .child-content {
            border: 1px solid #ff0066;
        }
    </style>

    <script src="../static/lib/vue.js"></script>
</head>

<body>

    <div id="app">
        <div class="parent-content">
            <h2>父组件内容</h2>
            <p>Messages: {{ messages | json }}</p>
        </div>

        <child-component></child-component>
    </div>

    <template id="child-component">
        <div class="child-content">
            <h2>子组件内容</h2>
            <input v-model="msg" />
            <button v-on:click="notify">Dispatch Event</button>
        </div>
    </template>

    <script>
        // 注册子组件
        Vue.component('child-component', {
            template: '#child-component',
            data: function () {
                return {
                    msg: ''
                }
            },
            methods: {
                notify: function () {
                    if (this.msg.trim()) {
                        Event.$emit('child-msg', this.msg)
                        this.msg = ''
                    }
                }
            }
        })

        //准备一个空的实例对象
        var Event = new Vue();

        // 初始化父组件
        new Vue({
            el: '#app',
            data: {
                messages: []
            },
            mounted() {
                //接收A组件的数据
                Event.$on("child-msg", function (msg) {
                    this.messages.push(msg);
                }.bind(this));
            }

        })
    </script>
</body>

</html>